const LogModel = require('../../model/Log');
const moment = require('moment')
const PointHistory = require('../../model/PointHistory')
const ManualChangePoint = require('../../model/ManualChangePoint')
const ExpenseHistory = require('../../model/ExpenseHistory')
const Order = require('../../model/Order')
const User = require('../../model/User.js')
const Store = require('../../model/Store')
const Voucher = require('../../model/Voucher');
const Member = require('../../model/Member');
const ObjectID = require('mongodb').ObjectID;
const MonthlyPoint = require('../../model/MonthlyPoint')

module.exports = {

    //获取日志列表
    getManualChangePointList: async (req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if(req.body.userId){
                let user = await User.findOne({isDelete:0,_id:ObjectID(req.body.userId)}).exec()
                option.openid = user.openid
            }
            if(req.body.cellphone){
                let user = await User.findOne({isDelete:0,cellphone:req.body.cellphone}).exec()
                if(user != null){
                    option.openid = user.openid
                }
            }
            let count = await ManualChangePoint.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let manualChangePointList = await ManualChangePoint.aggregate([
            {
                $match: option
            },
            {
                $skip: ((page - 1) * pageSize)
            },
            {
                $limit: pageSize
            },
            {
                $lookup: {
                    from: "user",
                    localField: 'openid',
                    foreignField: 'openid',
                    as: 'user'
                }
            },
            {
                $lookup: {
                    from: "adminUser",
                    localField: 'account',
                    foreignField: '_id',
                    as: 'account'
                }
            }
        ]).exec()
        manualChangePointList.forEach(async e => {
            e.user = e.user[0]
            e.account = e.account[0]
        });
        let result = {}
        result.total = count
        result.currentPage = page
        result.data = manualChangePointList
        result.pageSize = pageSize
        res.ok('查询成功', result)
        } catch (e) {
            next(e)
        }
    },

    monthlyPointStatistics: async (req, res, next) => {
        try {
            let startDate = new Date(moment().subtract(1, 'months').startOf('month'))
            let endDate = new Date(moment().subtract(1, 'months').endOf('month'))
            if(req.body.month){
                startDate = new Date(moment(req.body.month).startOf('month'))
                endDate = new Date(moment(req.body.month).endOf('month'))
            }
            // console.log(startDate,endDate)
            let option = {}
            option.isDelete = 0
            option.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            // let expenseHistory = await ExpenseHistory.find(option).exec()
            // let point = 0
            // expenseHistory.forEach(e => {
            //     if(e.verify == 0){
            //         point = point + e.pendingPoint
            //     }
            // })
            // console.log(point)
            let expenseHistory = await ExpenseHistory.aggregate([
                {
                  $match: option
                },
                {
                    $group:{_id:"$store",giftPoint:{$sum:"$earnPoints"},usedPoint:{$sum:"$point"}}
                },
                {
                    $lookup:{
                        from:"store",
                        localField:'_id',
                        foreignField:'_id',
                        as:'store'
                    },
                },
                {
                    $sort: {
                        _id: -1
                    }
                }
                ]).exec()
                expenseHistory.forEach(async e => {
                    e.store = e.store[0].name
                    let tempPoint = 0 
                    let storeId = e._id
                    let voucherOrderOption = {}
                    voucherOrderOption.isDelete = 0
                    voucherOrderOption.type = 1
                    voucherOrderOption.status = 1
                    voucherOrderOption.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
                    voucherOrderOption.store = {$in:storeId}
                    let voucherOrder = await Order.find(voucherOrderOption).exec()
                    voucherOrder.forEach(i =>{
                        // console.log(e.store,i.totalPoint)
                        tempPoint = tempPoint + i.totalPoint
                    })
                    e.voucherOrderPoint = tempPoint
                });
            let productPoint = 0
            let voucherPoint = 0
            let orderOption = {}
            orderOption.isDelete = 0
            // orderOption.status = 1
            orderOption.$or = [{ status: 1}, { status: 4}]
            orderOption.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            let orderList = await Order.find(orderOption).exec()
            orderList.forEach(e =>{
                    if(e.type == 0){
                        productPoint = productPoint + e.totalPoint
                    }else if(e.type == 1){
                        voucherPoint = voucherPoint + e.totalPoint
                    }
                })
            let manualChangePoint = 0
            let manualChangePointOption = {}
            manualChangePointOption.isDelete=0
            manualChangePointOption.$and = [{ expenseDate: { $gte: startDate } }, { expenseDate: { $lte: endDate } }]
            let manualChangePointList = await ManualChangePoint.find(manualChangePointOption).exec()
            manualChangePointList.forEach(e=>{
                manualChangePoint = manualChangePoint + e.amount
            })
            let totalPointOption = {}
            totalPointOption.isDelete = 0
            totalPointOption.expenseDate =  { $gte: endDate }
            // totalPointOption.$and = [{ expenseDate: { $gte: startDate } }, { expenseDate: { $lte: endDate } }]
            let totalPointList = await PointHistory.find(totalPointOption).exec()
            let totalGiftPoint = 0
            let totalUsedPoint = 0
            await totalPointList.forEach( e=>{
                if(e.type == 0){
                    totalGiftPoint = totalGiftPoint + e.amount
                }else if(e.type ==1){
                    totalUsedPoint = totalUsedPoint + e.amount
                }
            })
            let userlist = await Member.find({isDelete:0}).exec()
            let totalUserPoint = 0 
            await userlist.forEach( e=>{
                if(e.point){
                    totalUserPoint = totalUserPoint + e.point
                }
            })
            let monthlyPoint = await MonthlyPoint.findOne({month:endDate,isDelete:0}).exec()
                let result = {}
                result.expenseHistory = expenseHistory
                // if(monthlyPoint != null){
                //     result.productPoint = monthlyPoint.productPoint
                //     result.voucherPoint = monthlyPoint.voucherPoint
                //     result.manualChangePoint = monthlyPoint.manualChangePoint
                //     result.canUsePoint = monthlyPoint.canUsePoint
                // }else{
                    result.productPoint = productPoint
                    result.voucherPoint = voucherPoint
                    result.manualChangePoint = manualChangePoint
                    result.canUsePoint = totalUserPoint + totalUsedPoint - totalGiftPoint
                // }
                console.log(totalUserPoint,totalGiftPoint,totalUsedPoint,productPoint,voucherPoint,manualChangePoint)
                if(startDate <= new Date(moment("2020-07-01").startOf('month'))){
                    result.canUsePoint = 0
                }
                res.ok('查询成功', result)
        } catch (e) {
            next(e)
        }
    },


    canuUsePointCheck: async (req, res, next) => {
        try {
            let startdate = new Date("2020-12-01 00:00:00")
            let enddate = new Date("2021-02-01 00:00:00")
            let pointList = await PointHistory.find({isDelete:0,expenseDate:{$gte:startdate}}).exec()
            let expenseHistoryList = await ExpenseHistory.find({isDelete:0,verify:1,createdAt:{$gte:startdate}})
            let expensePoiont = 0
            let giftPoint = 0
            let usedPoint = 0
            expenseHistoryList.forEach(e=>{
                expensePoiont = expensePoiont+e.earnPoints
            })
            pointList.forEach(e=>{
                if(e.type == 0){
                    giftPoint = giftPoint+e.amount
                }else if(e.type == 1){
                    usedPoint = usedPoint+e.amount
                }
            })
            console.log(expensePoiont,giftPoint,usedPoint)
            res.ok('ok')
        } catch (e) {
            next(e)
        }
    },

    // canuUsePointCheck: async (req, res, next) => {
    //         try {
    //             let startdate = new Date("2020-12-01 00:00:00")
    //             let enddate = new Date("2021-02-01 00:00:00")
    //             allPointHistory = await PointHistory.find({isDelete:0,expenseDate:{$gte:startdate,$lte:enddate},expenseHistory:{$ne:null}}).populate("expenseHistory").exec()
    //             let addPoint = 0
    //             let subPoint = 0
    //             // allPointHistory.forEach(e=>{
    //             //     if(e.type == 0){
    //             //         addPoint = addPoint + e.amount
    //             //     }else if(e.type == 1){
    //             //         subPoint = subPoint + e.amount
    //             //     }
    //             //     // console.log(e._id)
    //             // })
    //             let tempIds = []
    //             let templist = allPointHistory.filter(e=>{return e.expenseHistory.isDelete == 0})
    //             templist.forEach(e=>{
    //                 if(e.type == 0){
    //                     addPoint = addPoint + e.amount
    //                     tempIds.push(String(e.expenseHistory._id))
    //                 }else if(e.type == 1){
    //                     subPoint = subPoint + e.amount
    //                 }
    //                 // console.log(e._id)
    //             })
    //             console.log(addPoint,subPoint)
    //             let expensePoints = 0
    //             allExpenseHistory = await ExpenseHistory.find({isDelete:0,createdAt:{$gte:startdate,$lte:enddate}}).exec()
    //             allExpenseHistory.forEach(e=>{
    //                 expensePoints =expensePoints + e.earnPoints
    //                 let index = tempIds.indexOf(String(e._id))
    //                 if(index == -1){
    //                     console.log('ok',e._id,e.earnPoints)
    //                 }
    //             })
    //             console.log(expensePoints)
    //             // templist = allPointHistory.filter(e=> {return e.type == 0})
    //             // templist.forEach(a=>{
    //             // })
    //             console.log(allPointHistory.length,allExpenseHistory.length)



    //             // let alluser = await Member.find({isDelete:0,createdAt:{$gte:startdate}}).exec()
    //             // let errorUserList = []
    //             // alluser.forEach(async user=>{
    //             //     let tempPoint = 0
    //             //     let oneUserPoint = await PointHistory.find({openid:user.openid,isDelete:0}).exec()
    //             //     tempPoint = tempPoint + user.point
    //             //     oneUserPoint.forEach(e=>{
    //             //         if(e.type === 0){
    //             //             tempPoint = tempPoint - e.amount
    //             //         }else if(e.type === 1){
    //             //             tempPoint = tempPoint + e.amount
    //             //         }
    //             //     })
    //             //     if(tempPoint != 0 ){
    //             //         console.log(user.openid,tempPoint)
    //             //     }
    //             // })
    //             res.ok('ok')
    //         } catch (e) {
    //             next(e)
    //         }
    //     },

    // voucherOrderAddStore: async (req, res, next) => {
    //     try {
    //         let orderList = await Order.find({isDelete:0}).exec()
    //         for(let i=0;i<orderList.length;i++){
    //             if(orderList[i].type ==1 && orderList[i].products[0].voucher != "5f55f2b47a5bb84685f3b179"){
    //                 let oneVoucher = await Voucher.findOne({_id:orderList[i].products[0].voucher}).exec()
    //                 // orderList[i].store = oneVoucher.store
    //                 // await orderList[i].save()
    //                 console.log(oneVoucher.title,orderList[i]._id)
    //             }
    //         }
    //         res.ok('获取优惠券成功')
    //     } catch (e) {
    //         next(e)
    //     }
    // },
};